#!/usr/bin/python3

# This script looks at the .apk files in the 'all_apks' folder,
# submits their hashes to andrototal.org to see if they're malicious,
# and sorts them into folders based on that ('malicious_apk' and 'benign_apk')
# (make sure those folders exist before running this)

import subprocess
import os
import json
import glob
from configparser import ConfigParser

def main():
    config = ConfigParser()
    config.read('config.ini')
    API_KEY = config.get('AMA', 'API_KEY')
    for apk in glob.glob('all_apks/*.apk'):
        if not os.path.isfile(apk[:-4] + '_andrototal.json'):
            print('Checking ' + apk)
            try:
                analysis = subprocess.check_output('./tools/andrototal_cli.py analysis -at-key {} {}'.format(API_KEY, apk.split('/')[1][:-4]), shell=True).decode('utf-8')
            except subprocess.CalledProcessError as e:
                print(str(e))
                continue
            with open(apk[:-4] + '_andrototal.json', 'w') as out_file:
                out_file.write(analysis)
        try:
            with open(apk[:-4] + '_andrototal.json') as json_file:
                analysis = json.load(json_file)
                if type(analysis) == str: raise ValueError
        except ValueError:
            with open('invalid_andrototal_responses', 'a') as out_file:
                out_file.write(apk.split('/')[1] + '\n')
            continue
        if all([test['result'] == 'NO_THREAT_FOUND' for test in analysis['tests']]):
            os.rename(apk, 'benign_apk/' + apk.split('/')[1])
        else:
            os.rename(apk, 'malicious_apk/' + apk.split('/')[1])

if __name__=='__main__':
    main()
